package com.lsl.rdf.utils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Objects;

/**
 * Created by lsl on 2021/6/22.
 */
public class RequestInfoUtil {

    /**
     * 获取主机地址
     */
    public static String getHostAddress() throws UnknownHostException {
        String hostAddress = InetAddress.getLocalHost().getHostAddress();
        if (!"".equals(hostAddress)) {
            String[] ipArr = hostAddress.split("\\.");
            hostAddress = "*.*." + ipArr[2] + "." + ipArr[3];
        }
        return hostAddress;
    }

    /**
     * 获取请求链接地址
     */
    public static String getRequestURL(HttpServletRequest request) {
        if (Objects.isNull(request)) {
            return "";
        }
        return request.getRequestURL().toString();
    }

    /**
     * 获取请求IP地址
     */
    public static String getRequestIp(HttpServletRequest request) {
        if (Objects.isNull(request)) {
            return "";
        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }

        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }

        return ip;
    }
}
